<template>
  <div>
       <Card>
           <div slot="title" style="display: flex; justify-content: space-between">
                <div style="display: flex">
                    <Tabs @on-click="switchTab" type="card">
                        <Tab-pane label="医疗设备" icon="medkit"></Tab-pane>
                        <Tab-pane label="科研设备" icon="ios-medical"></Tab-pane>
                    </Tabs>
                </div>
                <div>
                    <Tooltip content="新增设备类型">
                        <Button type="warning" @click="addModal=true" style=" margin-left: 8px"><Icon type="plus"></Icon> </Button>
                    </Tooltip>
                    <Tooltip content="排序和过滤后的数据">
                        <Button type="primary" @click="exportData(2)"><Icon type="funnel"></Icon> </Button>
                    </Tooltip>
                    <Tooltip content="原始数据">
                        <Button type="primary" @click="exportData(1)"><Icon type="ios-download"></Icon> </Button>
                    </Tooltip>
                </div>
            </div>
            <Table :context="self" :data="tableData" :columns="tableColumns" :loading="tableLoading" stripe ref="table"></Table>
            <div style="margin: 12px;overflow: hidden; font-size: 12px">
                <div style="float: right;">
                    <Page :total="tableCount" :current="currentPage" @on-change="changePage" show-total show-elevator></Page>
                </div>
            </div>
        </Card>
   
    <Modal
      :title="'新增设备类型'"
      v-model="addModal"
      :mask-closable="false"
      @on-ok="confirmFn('新增')">
      <Form :model="addForm" :label-width="80" ref="addV" :rules="addValidate">
        <Form-item label="类型名称" prop="category">
          <Input v-model="addForm.category" placeholder="请输入" style="width: 360px"></Input>
        </Form-item>
        <Form-item label="设备性质" prop="type">
          <Select v-model="addForm.type" style="width:360px">
            <Option value="0" label="医疗设备" style="width:360px">
              <span>医疗设备</span>
              <span style="float:right;color:#ccc"><Icon type="medkit"></Icon></span>
            </Option>
            <Option value="1" label="科研设备" style="width:360px">
              <span>科研设备</span>
              <span style="float:right;color:#ccc"><Icon type="ios-medical"></Icon></span>
            </Option>
          </Select>
        </Form-item>
        <Form-item label="图标" prop="icon" class="select-icon">
          <Select v-model="addForm.icon" style="width:330px">
            <Option :value="item.value" :label="item.label" :key="item.value" style="width:315px"
                    v-for="item in iconList">
              <span>{{item.label}}</span>
              <img :src="`https://yxys.io/icons/${item.value}.png`" width="20px" style="float: right">
            </Option>
          </Select>
          <div style="display: inline-block; padding: 5px; height: 32px;"><img
            :src="addForm.icon?`https://yxys.io/icons/${addForm.icon}.png`:' '" width="20px">
          </div>
        </Form-item>
        <Form-item label="类型描述" prop="desc">
          <Input v-model="addForm.desc" placeholder="请输入" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                 style="width: 360px" /> 
        </Form-item>
      </Form>
    </Modal>
    <Modal
      title="编辑现有设备类型"
      v-model="editModal"
      :mask-closable="false"
      @on-ok="confirmFn('编辑')">
      <Form :model="editForm" :label-width="120" ref="editV" :rules="editValidate">
        <Form-item label="类型名称" prop="category">
          <Input v-model="editForm.category" placeholder="请输入" style="width: 360px"></Input>
        </Form-item>
        <Form-item label="设备性质" prop="type">
          <Select v-model="editForm.type" style="width:360px">
            <Option value="0" label="医疗设备" style="width:360px">
              <span>医疗设备</span>
              <span style="float:right;color:#ccc"><Icon type="medkit"></Icon></span>
            </Option>
            <Option value="1" label="科研设备" style="width:360px">
              <span>科研设备</span>
              <span style="float:right;color:#ccc"><Icon type="ios-medical"></Icon></span>
            </Option>
          </Select>
        </Form-item>
        <Form-item label="图标" prop="icon" class="select-icon">
          <Select v-model="editForm.icon" style="width:330px">
            <Option :value="item.value" :label="item.label" :key="item.value" style="width:315px"
                    v-for="item in iconList">
              <span>{{item.label}}</span>
              <img :src="`https://yxys.io/icons/${item.value}.png`" width="20px" style="float: right">
            </Option>
          </Select>
          <div style="display: inline-block; padding: 5px; height: 32px;"><img
            :src="editForm.icon?`https://yxys.io/icons/${editForm.icon}.png`:' '" width="20px">
          </div>
        </Form-item>
        <Form-item label="类型描述" prop="desc">
          <Input v-model="editForm.desc" placeholder="请输入" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                 style="width: 360px" />
        </Form-item>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { tableColumns } from "./data/type";

export default {
  name: "Device-type",
  async mounted() {
    window.remove = this.remove;
    window.edit = this.edit;
    this.changeTab(0);
    this.iconList = (await this.$getRemoteData(`${this.$mapServer}/services/config/icon`)).data.icons.map(item => {
      this.iconDict[item.icon_name] = item.icon_path;
      this.iconNDict[item.icon_name] = item.icon_id;
      return { label: item.icon_name, value: item.icon_path };
    });
  },
  data() {
    return {
      tableColumns,
      tableLoading: false,
      self: this,
      addModal: false,
      editModal: false,
      confirmText: "",
      editRowIndex: "",
      confirmTextLong: "",
      currentTab: 0,
      currentPage: 1,
      iconList: [],
      iconDict: {},
      iconNDict: {},
      typeDict: ["医疗设备", "科研设备"],
      addValidate: {
        category: [
          {
            type: "string",
            required: true,
            message: "类型名称不能为空",
            trigger: "blur"
          }
        ],
        type: [
          { required: true, message: "设备性质不能为空", trigger: "on-change" }
        ],
        icon: [
          { required: true, message: "图标不能为空", trigger: "on-change" }
        ]
      },
      editValidate: {
        category: [
          {
            type: "string",
            required: true,
            message: "类型名称不能为空",
            trigger: "blur"
          }
        ],
        type  : [
          { required: true, message: "设备性质不能为空", trigger: "on-change" }
        ],
        icon: [
          { required: true, message: "图标不能为空", trigger: "on-change" }
        ]
      },
      addForm: {
        id: "",
        name: "",
        icon: "",
        type: "",
        desc: ""
      },
      editForm: {
        id: "",
        name: "",
        icon: "",
        type: "",
        desc: ""
      },
      tableData: [],
      tableCount: 0
    };
  },

  methods: {
    async changeTab() {
      this.tableLoading = true;
      let tmpTable = await this.$getRemoteData(`${this.$mapServer}/equip/services/config/deviceCategory/${this.currentTab}/0/10`);
      this.tableData = tmpTable.data.data;
      this.tableCount = parseInt(tmpTable.data.count);
      this.tableLoading = false;
    },
    async changePage(pageN) {
      this.currentPage = pageN;
      let tmpTable = await this.$getRemoteData(`${this.$mapServer}/equip/services/config/deviceCategory/${this.currentTab}/${(this.currentPage - 1) * 10}/10`);
      this.tableData = tmpTable.data.data;
      this.tableCount = parseInt(tmpTable.data.count);
    },
    exportData() {
      const tmpfilename = this.typeDict[this.currentTab];
      this.$refs.table.exportCsv({
        filename: tmpfilename + "设备类型子类表",
        original: false,
        columns: this.tableColumns.filter((col, index) => index < 6),
        data: this.tableData.filter((data, index) => {
          return true;
        })
      });
    },
    switchTab(n) {
      this.currentTab = n;
      this.changeTab();
    },
    edit(n) {
      this.editRowIndex = n;
      this.editModal = true;
      this.editForm = {
        id: this.tableData[n].id.toString(),
        category: this.tableData[n].name.toString(),
        icon: this.tableData[n].icon.toString(),
        type: this.tableData[n].type.toString(),
        desc: ""
      };
    },
    remove(n) {
      this.editRowIndex = n;
      this.confirmFn("删除");
    },
    confirmFn(text) {
      switch (text) {
        case "新增":
          this.$refs["addV"].validate(valid => {
            if (valid) {
              this.confirmTextLong = `${this.typeDict[this.addForm.type]}类型： "${this.addForm.category}" `;
              this.$Modal.confirm({
                title: `确认${text}设备类型`,
                content: `<p>确认${text}:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span> </p>`,
                loading: true,
                onOk: ()=>{this.finalConfirmFn(text)},
                onCancel: ()=>{this.cancelFn(text)},
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.addModal = true;
              });
            }
          });
          break;
        case "编辑":
          this.$refs["editV"].validate(valid => {
            if (valid) {
              this.confirmTextLong = `${this.typeDict[this.editForm.type]}（${this.editForm.category }）`;
              this.$Modal.confirm({
                title: `确认${text}设备类型`,
                content: `<p>确认${text}设备类型:<br><span style="font-weight: bold">${
                  this.confirmTextLong
                }</span> </p>`,
                loading: true,
                onOk: ()=>{this.finalConfirmFn(text)},
                onCancel: ()=>{this.cancelFn(text)},
              });
            } else {
              this.$Message.error("请注意需要填写的内容!");
              this.$nextTick(() => {
                this.editModal = true;
              });
            }
          });
          break;
        case "删除":
          this.confirmTextLong = `${this.typeDict[this.currentTab]}（${this.tableData[this.editRowIndex].name}）`;
          this.$Modal.confirm({
            title: `确认${text}设备类型`,
            content: `<p>确认${text}设备类型:<br><span style="font-weight: bold">${
              this.confirmTextLong
            }</span> </p>`,
            loading: true,
            onOk: ()=>{this.finalConfirmFn(text)},
            onCancel: ()=>{this.cancelFn(text)},
          });
          break;
      }
    },
    cancelFn(action) {
      this.$Modal.remove();
      switch (action) {
        case "新增":
          this.addModal = true;
          break;
        case "编辑":
          this.editModal = true;
          break;
        case "删除":
          break;
      }
    },
    async finalConfirmFn(action) {
      let result;
      try {
        switch (action) {
          case "新增":
            let tmpAdd = {
              id: Date.parse(new Date()),
              name: this.addForm.category,
              icon: this.addForm.icon,
              type: this.addForm.type,
              desc: this.addForm.desc
            };
            result = await this.$getRemoteData(`${this.$mapServer}/equip/services/config/addDeviceCategory`,
              {
                method: "POST",
                data: tmpAdd
              }
            );
            if (result.data.response_code == "000000") {
              this.$Message.success("新增设备类型成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("新增设备类型出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "编辑":
            let tmpEdit = {
              id: this.editForm.id,
              name: this.editForm.category,
              icon: this.editForm.icon,
              type: this.editForm.type,
              desc: this.editForm.desc
            };
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/config/updateDeviceCategory`,
              {
                method: "PUT",
                data: tmpEdit
              }
            );
            if (result.status === 200 || result.status === 201) {
              this.$Message.success("编辑设备类型成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("编辑设备类型出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
          case "删除":
            result = await this.$getRemoteData(
              `${this.$mapServer}/equip/services/config/deleteDeviceCategory?categoryId=${
                this.tableData[this.editRowIndex].id
              }`,
              {
                method: "DELETE"
              }
            );
            if (result.status === 200 || result.status === 201) {
              this.$Message.success("删除设备类型成功");
              this.changePage(this.currentPage);
            } else {
              this.$Message.error("删除设备类型出错，请检查网络情况");
            }
            this.$Modal.remove();
            break;
        }
      } catch (e) {
        console.error(e);
        this.$Message.error(`${action}设备类型出错，请检查网络情况`);
        this.$Modal.remove();
      }
    },
  }
};
</script>


<style>
.select-icon .ivu-form-item-content {
  height: 33px;
}

.select-icon .ivu-select {
  vertical-align: top;
}
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.search-select {
  width: 80px;
  position: absolute;
  top: 46px;
  right: 200px;
}

.search-input {
  position: absolute;
  top: 50px;
  right: 96px;
  width: 90px;
}

.device-tags .ivu-select-item {
  padding: 7px 5px;
}

.table-tab .ivu-tooltip {
  position: absolute;
  top: 48px;
}

.table-tab button:hover {
  color: #5cadff;
}

.table-tab button {
  padding: 0;
  font-size: 20px;
  color: #657180;
}

.tab-search-icon {
  right: 104px;
  transition: right 0.3s;
}

.tab-export-icon {
  right: 24px;
}

.tab-add-icon {
  right: 64px;
}

h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  /*margin: 0 10px;*/
}

a {
  color: #42b983;
}
</style>
